<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;

class AppVersion extends Model{

    //指定表名
    protected $table= 'app_version';
    //指定主键
    protected $primaryKey= 'id';
    //允许批量赋值字段
    protected $fillable = ['os_type','version','review_version','update_type','update_url','update_title','update_content','update_icon'];

    public $timestamps = true;

    /**
     * 获取版本信息(cache)
     * @param int $osType
     * @return array $versionInfo
     * */
    public static function getVersionInfo(int $osType){
        $key = config('cacheKey.version').$osType;
        $versionInfo = Redis::get($key);
        if (empty($versionInfo)){
            $versionInfo = AppVersion::where('os_type',$osType)->orderBy('id','desc')->first();
            if (empty($versionInfo)){
                Redis::setex($key,30,[]);
            }else{
                Redis::setex($key,86400,$versionInfo);
            }
        }else{
            $versionInfo = json_decode($versionInfo,true);
        }
        return $versionInfo??[];
    }

    /**
     * 更新缓存
     * @param int $osType
     * @return bool
     * */
    public static function updateVersionCache(int $osType)
    {
        //删除版本信息缓存
        $key = config('cacheKey.version').$osType;
        Redis::del($key);
        //刷新缓存
        self::getVersionInfo($osType);

        return true;
    }
}
